<template>
  <div class="online-query-form">
    <van-nav-bar class="header" left-arrow @click-left="onBack()">
      <template #title>
        <p style="font-size: 16px;color: #333333;font-weight: 400;">{{ form.formName }}</p>
      </template>
      <template #left>
        <van-icon name="arrow-left" size="18" color="#3B3938" />
      </template>
      <template #right>
        <i class="mobile-font icon-add"
          v-if="!showDelete && operationVisible(SysCustomWidgetOperationType.ADD) && !formReadOnly"
          style="font-size: 18px; color: #6C6C6C;"
          @click="handlerOperation(getOperation(SysCustomWidgetOperationType.ADD))"></i>

        <i class="mobile-font icon-delete"
          v-if="!showDelete && operationVisible(SysCustomWidgetOperationType.BATCH_DELETE) && !formReadOnly"
          style="font-size: 18px; color: #6C6C6C;margin-left: 10px;" @click="showDelete = true"></i>
        <span v-if="showDelete" class="cancel-btn" @click="onCancelDelete">取消</span>
      </template>
    </van-nav-bar>
    <online-filter-box style="background: white; padding: 0px 18px;" @refresh="onRefresh" @reset="onReset">
      <!-- 排序字段 -->
      <div slot="sort" style="display: flex; flex-direction: row; align-items: center; justify-content: flex-start;">
        <p class="sort-item" v-for="sortItem in sortList" :key="sortItem.id" @click="onSortChange(sortItem)"
          style="display: flex; flex-direction: row; align-items: center; justify-content: center;">
          <span class="sort-txt" :class="{ sortActive: sortInfoActive === sortItem.fieldName }">{{ sortItem.showName
          }}</span>
          <i :class="['mobile-font', sortItem.asc ? 'icon-asc' : 'icon-desc']"
            style="color:#707070; font-size:14px;"></i>
        </p>
      </div>
      <!-- 过滤字段 -->
      <online-custom-block subWidgetClass="filter-item" :widgetList="filterWidgetList" />
    </online-filter-box>
    <CustomList ref="cardList" style="padding: 0px 16px; flex-grow: 1;" :supportSelect="showDelete"
      :supportPullRefresh="showDelete" :loadData="loadTableData">
      <online-image-card slot-scope="scope" :widget="cardWidget" :supportSelect="showDelete" :rowData="scope.data"
        :masterTable="masterTable" :isSelect="itemIsSelect(scope.data)" style="background: white; margin: 15px 0px;"
        @click.native="handlerEditOperation(scope.data)" @select="onSelectChange">
        <!--
        <van-row slot="menu" type="flex" justify="end" style="border-top: 1px solid #E0E2E3; margin: 10px 0px; padding-top: 10px;">
          <van-icon name="delete-o" color="#DC4C33" size="14">
            删除
          </van-icon>
          <van-icon name="edit" color="#EE8133" size="14" style="margin-left: 10px;">
            修改
          </van-icon>
        </van-row>
        -->
      </online-image-card>
    </CustomList>
    <!-- 删除菜单 -->
    <van-row class="menu-box" type="flex" justify="space-between" align="center" v-if="showDelete">
      <van-checkbox :value="selectAll" shape="square" icon-size="14px" label-position="right" :label-disabled="true"
        @input="(val) => selectAllChange(val)">
        全部
      </van-checkbox>
      <van-icon name="delete-o" color="#EE0A24" size="14px" @click="handlerBathDelete">
        <span>
          删除{{ selectItemList.length > 0 ? ('(' + selectItemList.length + ')') : '' }}
        </span>
      </van-icon>
    </van-row>
    <!-- 弹出子表单 -->
    <van-popup v-if="showSubPage" v-model="showSubPage" position="right" get-container="body" :overlay="false"
      style="height: 100vh; width: 100vw; background: #F6F6F6;">
      <online-form :formId="subFormId" :rowData="editRowData" @close="onCloseSubForm" />
    </van-popup>
  </div>
</template>

<script>
import CustomList from '@/components/CustomList.vue';
import { OnlineFormMixins } from './onlineFormMixins.js';

export default {
  name: 'onlineQueryForm',
  props: {
    formConfig: {
      type: Object
    }
  },
  components: {
    CustomList
  },
  mixins: [OnlineFormMixins],
  provide() {
    return {
      form: () => {
        return {
          ...this.form,
          getWidgetValue: this.getWidgetValue,
          getWidgetVisible: this.getWidgetVisible,
          onValueChange: this.onValueChange,
          onWidgetValueChange: this.onWidgetValueChange,
          getDictDataList: this.getDictDataList,
          getDropdownParams: this.getDropdownParams,
          getPrimaryData: this.getPrimaryData,
          masterTable: this.masterTable
        }
      }
    }
  },
  data() {
    return {
      // 是否显示删除按钮
      showDelete: false,
      // 是否选中全部
      selectAll: false,
      // 删除选中项
      selectItemList: [],
      sortInfo: undefined,
      sortInfoActive: null
    }
  },
  methods: {
    onBack() {
      this.$router.go(-1);
    },
    handlerEditOperation(rowData) {
      if (this.showDelete) return;
      if (!this.operationVisible(this.SysCustomWidgetOperationType.EDIT) || this.formReadOnly) return;
      this.handlerOperation(this.getOperation(this.SysCustomWidgetOperationType.EDIT), rowData);
    },
    handlerBathDelete() {

      if (!this.showDelete) return;
      this.$dialog.confirm({
        title: '消息',
        message: '是否删除当前数据？'
      }).then(res => {
        this.handlerOperation(this.getOperation(this.SysCustomWidgetOperationType.BATCH_DELETE), this.selectItemList);
      }).catch(e => { });
    },
    onCloseSubForm(refresh) {
      this.showSubPage = false;
      if (refresh) this.onRefresh();
    },
    onRefresh() {
      this.onCancelDelete();
      if (this.$refs.cardList) this.$refs.cardList.reset();
    },
    onReset() {
      if (Array.isArray(this.filterWidgetList)) {
        this.filterWidgetList.forEach(widget => {
          this.onValueChange(widget, undefined);
        });
        if (this.$refs.cardList) this.$refs.cardList.reset();
      }
    },
    onCancelDelete() {
      this.showDelete = false;
      this.selectAll = false;
      this.selectItemList = [];
    },
    selectAllChange(val) {
      this.selectAll = val;
      if (this.$refs.cardList && val) {
        this.selectItemList = this.$refs.cardList.getDataList();
      } else {
        this.selectItemList = [];
      }
    },
    onSelectChange(data, val) {
      if (val) {
        this.selectItemList.push(data);
      } else {
        this.selectItemList = this.selectItemList.filter(item => {
          return item !== data;
        });
      }
    },
    itemIsSelect(data) {
      let find = false;
      for (let i = 0; i < this.selectItemList.length; i++) {
        if (this.selectItemList[i] === data) {
          find = true;
          break;
        }
      }
      return find;
    },
    onSortChange(sortInfo) {
      // console.log(sortInfo)
      if (sortInfo.asc == null) {
        sortInfo.asc = true;
      } else if (sortInfo.asc === true) {
        sortInfo.asc = false;
      } else if (sortInfo.asc === false) {
        // sortInfo.asc = undefined;
        sortInfo.asc = true;
      }
      if (sortInfo.asc != null) {
        this.sortInfoActive = sortInfo.fieldName
        this.sortInfo = {
          fieldName: sortInfo.fieldName,
          asc: sortInfo.asc
        }
      } else {
        this.sortInfo = undefined;
      }
      this.onRefresh();
    },
    async loadTableData(pageNum) {
      try {
        let table = this.form.tableMap.get(this.masterTable.tableId);
        if (table == null) {
          throw new Error('未配置主表');
        }

        let params = {
          datasourceId: table.datasource.datasourceId,
          filterDtoList: this.getQueryParams(this.filterWidgetList),
          pageParam: {
            pageNum: pageNum,
            pageSize: 20
          },
          orderParam: this.sortInfo == null ? [] : [this.sortInfo]
        }

        if (this.queryTable.relation != null) {
          params.relationId = table.relation.relationId;
          params.filterDtoList.push({
            tableName: this.queryTable.table.tableName,
            columnName: this.queryTable.relation.slaveColumn.columnName,
            filterType: this.SysOnlineColumnFilterType.EQUAL_FILTER,
            columnValue: (this.masterTableData || {})[this.queryTable.relation.masterColumn.columnName]
          });
        }
        // 脱敏设置
        params.ignoreMaskFields = this.getIgnoreMaskFields(this.queryTable);
        if (typeof this.queryTable.eventInfo[this.OnlineFormEventType.BEFORE_LOAD_TABLE_DATA] === 'function') {
          params = await this.queryTable.eventInfo[this.OnlineFormEventType.BEFORE_LOAD_TABLE_DATA](params);
        }
        if (params == null) throw new Error('取消加载数据');
        let res;
        if (table.relation != null) {
          res = await this.doUrl('/admin/online/onlineOperation/listByOneToManyRelationId/' + table.datasource.variableName, 'post', params);
        } else {
          res = await this.doUrl('/admin/online/onlineOperation/listByDatasourceId/' + table.datasource.variableName, 'post', params);
        }

        if (typeof this.queryTable.eventInfo[this.OnlineFormEventType.AFTER_LOAD_TABLE_DATA] === 'function') {
          res.data.dataList = await this.queryTable.eventInfo[this.OnlineFormEventType.AFTER_LOAD_TABLE_DATA](res.data.dataList);
        }
        return {
          dataList: res.data.dataList,
          totalCount: res.data.totalCount
        };
      } catch (e) {
        console.error(e);
        throw e;
      }
    }
  },
  computed: {
    form() {
      return this.buildFormConfig(this.formConfig);
    },
    queryTable() {
      return this.formConfig.tableWidget;
    },
    cardWidget() {
      return this.queryTable.childWidgetList[0];
    },
    filterWidgetList() {
      return this.queryTable.childWidgetList.slice(1);
    },
    sortList() {
      return this.queryTable.props.orderList.map(item => {
        let table = this.form.tableMap ? this.form.tableMap.get(item.tableId) : null;
        let column = this.form.columnMap ? this.form.columnMap.get(item.columnId) : null;
        if ((this.masterTable || {}).tableId === (table || {}).tableId) {
          // 主表字段
          return {
            ...item,
            fieldName: column.columnName,
            asc: undefined
          }
        } else {
          // 从表字段
          return {
            ...item,
            fieldName: table.tableName + '.' + column.columnName,
            asc: undefined
          }
        }
      });
    }
  },
  created() {
    this.isReady = false;
    this.initPage();
    this.initFormWidgetList();
    if (typeof this.form.eventInfo[this.OnlineFormEventType.AFTER_CREATE_FORM] === 'function') {
      this.form.eventInfo[this.OnlineFormEventType.AFTER_CREATE_FORM]();
    }
    this.initWidgetLinkage(this.form.formType);
    this.isReady = true;
  }
}
</script>

<style scoped>
.online-query-form {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #F6F7F9;
}

.menu-box {
  flex-grow: 0;
  flex-shrink: 0;
  width: 100%;
  padding: 16px;
  flex-wrap: nowrap;
  background: white;
  box-sizing: border-box;
}

.menu-box>>>.van-radio__label {
  font-size: 14px;
  color: #666666;
}

.van-icon-sort:before {
  content: none;
}

.sort-item+.sort-item {
  margin-left: 8px;
}

.sort-txt {
  font-size: 14px;
  color: #707070;
  margin-right: 1px;
}

.sortActive {
  color: #333333;
  /* font-size: 14px; */
}

.van-icon-sort:after {
  content: '\e721';
}

.cancel-btn {
  cursor: pointer;
  font-size: 14px;
  color: #999999;
}
</style>

<style>
.filter-item+.filter-item {
  margin-top: 10px;
}
</style>
